package com.zcy.gift.exception;


import com.zcy.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理类
 * 作用: controller如果要抛出异常,全部都会走到这个类来,后续controller层里面就不用再写try catch
 */
@RestControllerAdvice   // 这个注解的意思:在controller的方法运行前后做一些事情
public class GlobalExceptionHandler {

    /**
     * 以下这个方法是处理业务异常的,那么@ExceptionHandler就要捕获BusinessException
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.error(e.getMessage(),e.getCode());
    }

    /**
     * 捕获 jsr303校验的错误信息
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer str = new StringBuffer();
        for (ObjectError allError : allErrors) {
            String defaultMessage = allError.getDefaultMessage();
            str.append(defaultMessage);
            str.append("!");
        }
        return AjaxResult.error(str.toString(),ResponseCode.RESPONSE_CODE_40010.getCode());
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.error(ResponseCode.RESPONSE_CODE_500.getMessage(),ResponseCode.RESPONSE_CODE_500.getCode());
    }
}
